/**
 *    Copyright 2012 Geensoft S.A.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **/
package ar.com.greensoft.neosystem.admin.users;

import java.io.Serializable;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.validation.constraints.AssertTrue;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import org.jboss.logging.Logger;

import ar.com.greensoft.jeecommons.web.jsf.util.FacesUtil;
import ar.com.greensoft.jeecommons.web.jsf.util.JSFMenuUtil;
import ar.com.greensoft.jeecommons.web.jsf.util.ResourceBundleUtil;
import ar.com.greensoft.neosystem.crm.web.beans.NavigationConstants;
import ar.com.greensoft.neosystem.model.Authority;
import ar.com.greensoft.neosystem.model.User;
import ar.com.greensoft.neosystem.services.ServiceException;
import ar.com.greensoft.neosystem.services.UserExistsException;
import ar.com.greensoft.neosystem.services.UserService;
import ar.com.greensoft.neosystem.util.ApplicationRoles;

/**
 * @author Jorge E. Villaverde
 *
 */
@ViewScoped
@ManagedBean
public class CreateUserBean implements Serializable, NavigationConstants, ApplicationRoles {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -8760762921614151085L;

	private static final Logger logger = Logger.getLogger(CreateUserBean.class);

	private static final String USER_EXISTS_MESSAGE_KEY = "ar.com.greensoft.neo.web.jsf.beans.admin.users.USER_EXIST_ERROR";

	@EJB
	private UserService userService;

	@NotNull
	@Size(min = 1, max = 50)
	private String username;
	@NotNull
	@Size(min = 1, max=50)
	private String password;
	@NotNull
	@Size(min = 1, max=50)
	private String passwordRetry;
	
	private List<String> authorities;
	
	private List<String> selectedAuthorities = new ArrayList<String>();
	
    /**
     * Cancel View
     */
    protected String cancelView;
    
    /**
     * Return View
     */
    protected String persistReturnView;
		
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getPasswordRetry() {
		return passwordRetry;
	}
	public void setPasswordRetry(String passwordRetry) {
		this.passwordRetry = passwordRetry;
	}

	public void clearData() {
		this.username = null;
		this.password = null;
		this.passwordRetry = null;
		this.selectedAuthorities = null;
	}
	
	@AssertTrue(message="{ar.com.greensoft.PasswordDoNotMatch.message}")
	public boolean isPasswordMatch(){
		if(password == null || passwordRetry == null)
			return false;
		return password.equals(passwordRetry);
	}
	
	public String createUser(){
		if(logger.isTraceEnabled())
			logger.trace("Creating User: " + username);
		
		User user;
		try {
			user = userService.createUser(username, password);
			if(user != null){
				for(String authorityName : selectedAuthorities){
					Authority authority = new Authority();
					authority.setUser(user);
					authority.setAuthority(authorityName);
					userService.grantAuthority(authority);
				}
				user = userService.findUserByUsername(user.getUsername());
			}
			
			if(logger.isTraceEnabled())
				logger.trace("User " + username + " CREATED.");
			
			return INDEX_ACTION;
		} catch (UserExistsException e) {
			String localizedMessage = ResourceBundleUtil.getResourceBundleString(
					USER_EXISTS_MESSAGE_KEY, 
					FacesContext.getCurrentInstance().getViewRoot().getLocale());
			String message = MessageFormat.format(localizedMessage, e.getUsername());
			FacesUtil.addErrorMessage(message);
		} catch (ServiceException e) {
			logger.error(e.getMessage());
		}		
		return null;
	}
	
	public String showCreate(){
		FacesContext ctx = FacesContext.getCurrentInstance();
		cancelView = ctx.getViewRoot().getViewId();
		return JSFMenuUtil.buildMenuPath(ADMIN_PATH, "users", CREATE_ACTION);
	}

	public String cancel() {
		if(cancelView != null && !cancelView.isEmpty()) 
			return cancelView + JSFMenuUtil.JSF_REDIRECT_ESCAPED;
		return showCreate();		
	}
	
	
	public String getCancelView() {
		return cancelView;
	}

	public void setCancelView(String cancelView) {
		this.cancelView = cancelView;
	}

	public String getPersistReturnView() {
		return persistReturnView;
	}

	public void setPersistReturnView(String persistReturnView) {
		this.persistReturnView = persistReturnView;
	}

	public List<String> getAuthorities() {
		return authorities;
	}

	public void setAuthorities(List<String> authorities) {
		this.authorities = authorities;
	}

	public List<String> getSelectedAuthorities() {
		return selectedAuthorities;
	}

	public void setSelectedAuthorities(List<String> selectedAuthorities) {
		this.selectedAuthorities = selectedAuthorities;
	}

}
